package com.ruoyi.web.controller.module;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.module.*;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.estate.RepairRecord;
import com.ruoyi.system.domain.module.mer.Mer;
import com.ruoyi.system.domain.module.product.ProductOrder;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.property.PropertyFeeOrder;
import com.ruoyi.system.domain.module.vo.FirstDataVo;
import com.ruoyi.system.domain.module.wx.UserIntegralRecord;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.domain.vo.MonthMoneyVo;
import com.ruoyi.system.service.module.*;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.estate.IRepairRecordService;
import com.ruoyi.system.service.module.mer.IMerService;
import com.ruoyi.system.service.module.product.IProductOrderService;
import com.ruoyi.system.service.module.property.IPropertyFeeOrderService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.wx.IUserIntegralRecordService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.web.controller.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 图表 统计 数据
 *
 * @author ruoyi
 * @date 2021-08-18
 */
@Validated
@Api(value = "图表通用", tags = {"图表通用"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/chart")
public class ChartController extends BaseController {

	private final IEstateService estateService;
	private final IPropertyService propertyService;
	private final IWxUserService wxUserService;
	private final IProductOrderService productOrderService;
	private final IPropertyFeeOrderService propertyFeeOrderService;
	private final IRepairRecordService repairRecordService;
	private final IMerService merService;
	private final IParameterService parameterService;
	private final IUserIntegralRecordService userIntegralRecordService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

	/**
	 * 数据大屏页数据
	 */
	@ApiOperation("数据大屏页数据")
	@GetMapping("/data/view/center")
	public AjaxResult<Map<String,Object>> dataViewCenter(@Validated Estate estate) {
//		SysUser sysUser = getUser();
		Map<String,Object> map = new HashMap<>();

		Parameter parameter = parameterService.getParameterById(1);
		map.put("dateViewTitle",parameter.getDataViewTitle());

		QueryWrapper<Estate> qwEstate = new QueryWrapper<>();
		List<Estate> estates = estateService.list(qwEstate);
		//小区数量
		map.put("estates",estates);
		map.put("estateCount",estates.size() * 3);


		QueryWrapper<Mer> qwMer = new QueryWrapper<>();
		qwMer.eq("state",0);
		List<Mer> mers = merService.list(qwMer);
		for (Mer mer  : mers){
			mer.setShopLogo(imgUrl + mer.getShopLogo());
		}

		map.put("mers",mers);
		map.put("merCount",mers.size() * 3);


		//今日商家订单数
		/**
		 * 订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价
		 * 5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
		 */
		QueryWrapper<ProductOrder> qwProductOrder = new QueryWrapper<>();
		qwProductOrder.select("id");
		Integer[] productStates = { 2, 3 };
		qwProductOrder.in("status",Arrays.asList(productStates));
		qwProductOrder.between("create_time",DateUtils.getDate() + " 00:00:00" ,DateUtils.getDate() + " 23:59:59");
		long productOrderCount = productOrderService.count(qwProductOrder);
		map.put("productOrderCount",productOrderCount * 3);


		return AjaxResult.success(map);
	}

	/**
	 * 数据大屏页数据
	 */
	@ApiOperation("数据大屏页数据")
	@GetMapping("/data/view/center/charts")
	public AjaxResult<Map<String,Object>> dataViewCenterCharts(@Validated Estate estate) {
		Map<String,Object> map = new HashMap<>();

		long userTotalCount = wxUserService.count();
		map.put("userTotalCount",userTotalCount + 100000);

		QueryWrapper<WxUser> qwLogin = new QueryWrapper<>();
		qwLogin.ge("last_active_time",DateUtils.getDay() + " 00:00:00");
		long todayLoginCount = wxUserService.count(qwLogin);
		map.put("todayLoginCount",todayLoginCount * 3);

		QueryWrapper<WxUser> qwCreate = new QueryWrapper<>();
		qwCreate.ge("create_time",DateUtils.getDay() + " 00:00:00");
		long todayCreateCount = wxUserService.count(qwCreate);
		map.put("todayCreateCount",todayCreateCount * 10);


		return AjaxResult.success(map);
	}


	/**
     * 查询小区列列表
     */
    @ApiOperation("查询小区列列表")
    @GetMapping("/data/count")
    public AjaxResult<FirstDataVo> dataCount(@Validated Estate estate) {
		SysUser sysUser = getUser();
		FirstDataVo firstDataVo = new FirstDataVo();

		firstDataVo.setUserType(sysUser.getUserType());
		firstDataVo.setRoleId(sysUser.getRoleId());

        QueryWrapper<Estate> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(estate.getEstateName())){
            qw.eq("estate_name",estate.getEstateName());
        }
        if(estate.getPropertyId() != null){
			qw.eq("property_id",estate.getPropertyId());
		}

        //所有用户量
        long wxAllUserCount = wxUserService.count();
		firstDataVo.setUserAllCount(wxAllUserCount);



		QueryWrapper<WxUser> qwTodayNewUser = new QueryWrapper<>();
		qwTodayNewUser.select("id");
		qwTodayNewUser.ge("create_time",DateUtils.getTodayDateTimeZero());
		long newUser = wxUserService.count(qwTodayNewUser);
		firstDataVo.setUserNewCount(newUser);

		//报修量
		QueryWrapper<RepairRecord> qwRepair = new QueryWrapper<>();
		qwRepair.select("id");
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				qwRepair.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				qwRepair.eq("estate_id",sysUser.getEstateId());
			}
		}
		qwRepair.between("create_time", DateUtils.getDateTimeByDayCountBefore(-30), new Date());
		long repairCount = repairRecordService.count(qwRepair);
		firstDataVo.setRepairCount(repairCount);

		//近7天新增用户量
		QueryWrapper<WxUser> qwWxUser = new QueryWrapper<>();
		qwWxUser.select("id");
		qwWxUser.between("create_time", DateUtils.getDateTimeByDayCountBefore(-7), new Date());
		long wxUserCount7 = wxUserService.count(qwWxUser);
		firstDataVo.setUserNewCount7(wxUserCount7);

		//物业公司的今日分润
		if(sysUser.getUserType() == 2) {//物业公司
			Map<String,Object> mapOrder = new HashMap<>();
			mapOrder.put("begin_time", DateUtils.getDate() + " 00:00:00");
			mapOrder.put("end_time", DateUtils.getDate() + " 23:59:59");
			// 总分润
			double fenRunProperty = productOrderService.selectFenRunProperty(mapOrder);
			firstDataVo.setTodayFenRun(fenRunProperty);
		}



		//今日订单数
		QueryWrapper<ProductOrder> orderToday = new QueryWrapper<>();
		orderToday.select("id");
		orderToday.between("create_time", DateUtils.getTodayDateTimeZero(), new Date());
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				orderToday.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				orderToday.eq("estate_id",sysUser.getEstateId());
			} else if(sysUser.getUserType() == 4) {//商家
				List<Integer> merIds = new ArrayList<>();
				Map<String,Object> map = new HashMap<>();
				map.put("sys_user_id",sysUser.getUserId());
				List<Mer> list = merService.selectMerListByUserId(map);
				if(CollUtil.isNotEmpty(list)){
					for (Mer mer : list){
						merIds.add(mer.getId());
					}
				}
				if(merIds.size() > 0){
					orderToday.in("mer_id",merIds);
				}else{
					orderToday.in("mer_id",sysUser.getMerId());
				}
			}
		}
		long orderTodayCount = productOrderService.count(orderToday);
		firstDataVo.setOrderTodayCount(orderTodayCount);


		//近7日订单数
		QueryWrapper<ProductOrder> order7 = new QueryWrapper<>();
		order7.select("id");
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				order7.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				order7.eq("estate_id",sysUser.getEstateId());
			} else if(sysUser.getUserType() == 4) {//商家
//				order7.eq("mer_id",sysUser.getMerId());
				List<Integer> merIds = new ArrayList<>();
				Map<String,Object> map = new HashMap<>();
				map.put("sys_user_id",sysUser.getUserId());
				List<Mer> list = merService.selectMerListByUserId(map);
				if(CollUtil.isNotEmpty(list)){
					for (Mer mer : list){
						merIds.add(mer.getId());
					}
				}
				if(merIds.size() > 0){
					order7.in("mer_id",merIds);
				}else{
					order7.in("mer_id",sysUser.getMerId());
				}
			}
		}

		order7.between("create_time", DateUtils.getDateTimeByDayCountBefore(-7), new Date());
		long order7Count = productOrderService.count(order7);
		firstDataVo.setOrder7Count(order7Count);

		//今日交易额
		Map<String,Object> mapOrder = new HashMap<>();
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				mapOrder.put("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				mapOrder.put("estate_id",sysUser.getEstateId());
			} else if(sysUser.getUserType() == 4) {//商家
//				mapOrder.put("mer_id",sysUser.getMerId());
				mapOrder.put("sys_user_id",sysUser.getMerId());
			}
		}
		mapOrder.put("begin_time",DateUtils.getTodayDateTimeZero());
		mapOrder.put("end_time",new Date());
		double orderMoneyToday = productOrderService.selectTotalMoneyByTime(mapOrder);
		firstDataVo.setTodayMoney(orderMoneyToday);


		//近7日交易额
		Map<String,Object> mapOrder7 = new HashMap<>();
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				mapOrder7.put("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				mapOrder7.put("estate_id",sysUser.getEstateId());
			} else if(sysUser.getUserType() == 4) {//商家
				mapOrder7.put("mer_id",sysUser.getMerId());
				mapOrder7.put("sys_user_id",sysUser.getMerId());
			}
		}
		mapOrder7.put("begin_time",DateUtils.getDateTimeByDayCountBefore(-7));
		mapOrder7.put("end_time",new Date());
		double orderMoney7 = productOrderService.selectTotalMoneyByTime(mapOrder7);
		firstDataVo.setMoney7(orderMoney7);


		List<String> monthDay = new ArrayList<>();
		List<Double> monthMoney = new ArrayList<>();
		List<Integer> monthOrderCount = new ArrayList<>();
		Map<String,Object> mapOrderMoneyChart = new HashMap<>();
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				mapOrderMoneyChart.put("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				mapOrderMoneyChart.put("estate_id",sysUser.getEstateId());
			} else if(sysUser.getUserType() == 4) {//商家
				mapOrderMoneyChart.put("mer_id",sysUser.getMerId());
				mapOrderMoneyChart.put("sys_user_id",sysUser.getMerId());
			}

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			int month = calendar.get(Calendar.MONTH);
			int day = calendar.get(Calendar.DAY_OF_MONTH);
			Date firstDay = DateUtils.getDayOfMonth(month, 0, 1);
			Date lastDay = DateUtils.getDayOfMonth(month, 1, 0);
			mapOrderMoneyChart.put("begin_time",firstDay);
			mapOrderMoneyChart.put("end_time",lastDay);
			List<MonthMoneyVo> listMoneyChart = productOrderService.selectTotalMoneyByDay(mapOrderMoneyChart);
			if(CollUtil.isNotEmpty(listMoneyChart)){
				for (MonthMoneyVo monthMoneyVo : listMoneyChart){
					monthDay.add(monthMoneyVo.getTime().substring(8,10) + "日");
					monthMoney.add(monthMoneyVo.getMoney());
					monthOrderCount.add(monthMoneyVo.getCount());
				}
			}
			firstDataVo.setMonthDay(monthDay);
			firstDataVo.setMonthSaleMoney(monthMoney);
			firstDataVo.setMonthOrderCount(monthOrderCount);
		}


        return AjaxResult.success(firstDataVo);
    }


	/**
	 * 查询小区列列表
	 */
	@ApiOperation("查询小区列列表")
	@GetMapping("/navbar/count")
	public AjaxResult<FirstDataVo> NavBarCount(@Validated Estate estate) {
		SysUser sysUser = getUser();
		FirstDataVo firstDataVo = new FirstDataVo();

		firstDataVo.setUserType(sysUser.getUserType());
		firstDataVo.setRoleId(sysUser.getRoleId());
//		QueryWrapper<Estate> qw = new QueryWrapper<>();
//		if(StrUtil.isNotEmpty(estate.getEstateName())){
//			qw.eq("estate_name",estate.getEstateName());
//		}
//		if(estate.getPropertyId() != null){
//			qw.eq("property_id",estate.getPropertyId());
//		}

		//报修量
		QueryWrapper<RepairRecord> qwRepair = new QueryWrapper<>();
		qwRepair.select("id");
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				qwRepair.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				qwRepair.eq("estate_id",sysUser.getEstateId());
			}
		}
		qwRepair.between("create_time", DateUtils.getDateTimeByDayCountBefore(-30), new Date());
		long repairCount = repairRecordService.count(qwRepair);
		firstDataVo.setRepairCount(repairCount);

		//今日订单数
		QueryWrapper<ProductOrder> orderToday = new QueryWrapper<>();
		orderToday.select("id");
		orderToday.between("create_time", DateUtils.getTodayDateTimeZero(), new Date());
		orderToday.eq("status",2);
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				orderToday.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				orderToday.eq("estate_id",sysUser.getEstateId());
			} else if(sysUser.getUserType() == 4) {//商家
				List<Integer> merIds = new ArrayList<>();
				Map<String,Object> map = new HashMap<>();
				map.put("sys_user_id",sysUser.getUserId());
				List<Mer> list = merService.selectMerListByUserId(map);
				if(CollUtil.isNotEmpty(list)){
					for (Mer mer : list){
						merIds.add(mer.getId());
					}
				}
				if(merIds.size() > 0){
					orderToday.in("mer_id",merIds);
				}else{
					orderToday.in("mer_id",sysUser.getMerId());
				}
			}
		}
		long orderTodayCount = productOrderService.count(orderToday);
		firstDataVo.setOrderTodayCount(orderTodayCount);



		//今日物业费订单数
		QueryWrapper<UserIntegralRecord> integralQw = new QueryWrapper<>();
		integralQw.select("id");
		integralQw.between("create_time", DateUtils.getTodayDateTimeZero(), new Date());
//		integralQw.eq("state",0);
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				integralQw.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				integralQw.eq("estate_id",sysUser.getEstateId());
			}
		}
//		long integralOrders = userIntegralRecordService.count(integralQw);
//		firstDataVo.setYdOrderCount(integralOrders);


		//今日物业费订单数
		QueryWrapper<PropertyFeeOrder> orderFeeToday = new QueryWrapper<>();
		orderFeeToday.select("id");
		orderFeeToday.between("create_time", DateUtils.getTodayDateTimeZero(), new Date());
		orderFeeToday.eq("state",0);
		if(sysUser!=null){
			if(sysUser.getUserType() == 2){//物业公司
				orderFeeToday.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				orderFeeToday.eq("estate_id",sysUser.getEstateId());
			}
		}
		long orderFeeTodayCount = propertyFeeOrderService.count(orderFeeToday);
		firstDataVo.setPropertyOrderCount(orderFeeTodayCount);


		return AjaxResult.success(firstDataVo);
	}



	/**
	 *  物业 数据大屏页数据
	 */
	@ApiOperation("数据大屏页数据")
	@GetMapping("/data/view/property/center")
	public AjaxResult<Map<String,Object>> dataViewCenterProperty(@Validated Estate estate) {
//		SysUser sysUser = getUser();
		Map<String,Object> map = new HashMap<>();

		Property property = propertyService.findById(estate.getPropertyId());
		if(property != null){
			map.put("dateViewTitle", property.getDataViewTitle());
		}

		QueryWrapper<Estate> qwEstate = new QueryWrapper<>();
		List<Estate> estates = estateService.list(qwEstate);
		//小区数量
		map.put("estates",estates);
		map.put("estateCount",estates.size() * 3);



		QueryWrapper<RepairRecord> qw = new QueryWrapper<>();
		qw.eq("property_id", estate.getPropertyId());
		qw.orderByDesc("create_time");
		qw.last("limit 10");
		List<RepairRecord> repairRecords = repairRecordService.list(qw);

		map.put("repairRecords", repairRecords);


		QueryWrapper<Mer> qwMer = new QueryWrapper<>();
		qwMer.eq("state",0);
		List<Mer> mers = merService.list(qwMer);
		for (Mer mer  : mers){
			mer.setShopLogo(imgUrl + mer.getShopLogo());
		}

		map.put("mers",mers);
		map.put("merCount",mers.size() * 3);


		//今日商家订单数
		/**
		 * 订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价
		 * 5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
		 */
		QueryWrapper<ProductOrder> qwProductOrder = new QueryWrapper<>();
		qwProductOrder.select("id");
		Integer[] productStates = { 2, 3 };
		qwProductOrder.in("status",Arrays.asList(productStates));
		qwProductOrder.between("create_time",DateUtils.getDate() + " 00:00:00" ,DateUtils.getDate() + " 23:59:59");
		long productOrderCount = productOrderService.count(qwProductOrder);
		map.put("productOrderCount",productOrderCount * 3);


		return AjaxResult.success(map);
	}



	/**
	 *  物业 数据大屏页数据
	 */
	@ApiOperation("数据大屏页数据")
	@GetMapping("/data/view/property/repair/record")
	public AjaxResult<Map<String,Object>> dataViewCenterPropertyRepairRecord(@Validated Estate estate) {
//		SysUser sysUser = getUser();
		Map<String,Object> map = new HashMap<>();

		QueryWrapper<RepairRecord> qw = new QueryWrapper<>();
		qw.eq("property_id", estate.getPropertyId());

		//状态 0 - 待处理  1 - 已抢单 -  2 - 处理结束  3 - 结束完成 已完成
		qw.ne("state", 3);
		qw.orderByDesc("create_time");
		qw.last("limit 10");
		List<RepairRecord> repairRecords = repairRecordService.list(qw);

		map.put("repairRecords", repairRecords);

		return AjaxResult.success(map);
	}




}
